{% extends "base.html" %}

{% block title %}RAG系统调试 - 乳腺癌预测系统{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-warning text-dark">
                    <h4 class="mb-0">
                        <i class="fas fa-bug"></i> RAG系统调试页面
                    </h4>
                    <small>用于诊断RAG系统问题</small>
                </div>
                <div class="card-body">
                    <!-- 系统状态 -->
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <h5>系统状态检查</h5>
                            <button class="btn btn-primary" onclick="checkSystemStatus()">检查系统状态</button>
                            <div id="system-status" class="mt-2"></div>
                        </div>
                        <div class="col-md-6">
                            <h5>RAG系统测试</h5>
                            <button class="btn btn-success" onclick="testRAGSystem()">测试RAG系统</button>
                            <div id="rag-test" class="mt-2"></div>
                        </div>
                    </div>

                    <!-- 问答测试 -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <h5>问答测试</h5>
                            <div class="input-group">
                                <input type="text" id="test-question" class="form-control" placeholder="输入测试问题..." value="乳腺癌有哪些症状？">
                                <div class="input-group-append">
                                    <button class="btn btn-info" onclick="testQuestion()">测试问答</button>
                                </div>
                            </div>
                            <div id="question-result" class="mt-2"></div>
                        </div>
                    </div>

                    <!-- 详细日志 -->
                    <div class="row">
                        <div class="col-12">
                            <h5>详细日志</h5>
                            <div id="debug-log" style="background-color: #f8f9fa; padding: 15px; border-radius: 5px; max-height: 300px; overflow-y: auto; font-family: monospace; font-size: 12px;"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function log(message) {
    const logDiv = document.getElementById('debug-log');
    const timestamp = new Date().toLocaleTimeString();
    logDiv.innerHTML += `[${timestamp}] ${message}\n`;
    logDiv.scrollTop = logDiv.scrollHeight;
}

function checkSystemStatus() {
    log('开始检查系统状态...');
    const statusDiv = document.getElementById('system-status');
    statusDiv.innerHTML = '<div class="spinner-border spinner-border-sm" role="status"></div> 检查中...';
    
    fetch('/api/rag/categories')
    .then(response => {
        log(`API响应状态: ${response.status}`);
        return response.json();
    })
    .then(data => {
        if (data.error) {
            log(`API错误: ${data.error}`);
            statusDiv.innerHTML = `<div class="alert alert-danger">API错误: ${data.error}</div>`;
        } else {
            log(`API成功: 找到 ${data.categories.length} 个分类`);
            statusDiv.innerHTML = `<div class="alert alert-success">✓ 系统正常，找到 ${data.categories.length} 个知识分类</div>`;
        }
    })
    .catch(error => {
        log(`网络错误: ${error.message}`);
        statusDiv.innerHTML = `<div class="alert alert-danger">网络错误: ${error.message}</div>`;
    });
}

function testRAGSystem() {
    log('开始测试RAG系统...');
    const testDiv = document.getElementById('rag-test');
    testDiv.innerHTML = '<div class="spinner-border spinner-border-sm" role="status"></div> 测试中...';
    
    fetch('/api/rag/ask', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ question: '测试问题' })
    })
    .then(response => {
        log(`RAG API响应状态: ${response.status}`);
        return response.json();
    })
    .then(data => {
        if (data.error) {
            log(`RAG API错误: ${data.error}`);
            testDiv.innerHTML = `<div class="alert alert-danger">RAG系统错误: ${data.error}</div>`;
        } else {
            log(`RAG API成功: 置信度 ${data.confidence}`);
            testDiv.innerHTML = `<div class="alert alert-success">✓ RAG系统正常，置信度: ${data.confidence}</div>`;
        }
    })
    .catch(error => {
        log(`RAG网络错误: ${error.message}`);
        testDiv.innerHTML = `<div class="alert alert-danger">RAG网络错误: ${error.message}</div>`;
    });
}

function testQuestion() {
    const question = document.getElementById('test-question').value.trim();
    if (!question) return;
    
    log(`测试问题: ${question}`);
    const resultDiv = document.getElementById('question-result');
    resultDiv.innerHTML = '<div class="spinner-border spinner-border-sm" role="status"></div> 思考中...';
    
    fetch('/api/rag/ask', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ question: question })
    })
    .then(response => {
        log(`问题API响应状态: ${response.status}`);
        return response.json();
    })
    .then(data => {
        if (data.error) {
            log(`问题API错误: ${data.error}`);
            resultDiv.innerHTML = `<div class="alert alert-danger">错误: ${data.error}</div>`;
        } else {
            log(`问题API成功: 获得答案`);
            let html = `<div class="alert alert-success">`;
            html += `<strong>答案:</strong><br>${data.answer.replace(/\n/g, '<br>')}`;
            if (data.sources && data.sources.length > 0) {
                html += `<br><strong>来源:</strong><br>`;
                data.sources.forEach((source, index) => {
                    html += `${index + 1}. ${source.title} (${source.category})<br>`;
                });
            }
            html += `</div>`;
            resultDiv.innerHTML = html;
        }
    })
    .catch(error => {
        log(`问题网络错误: ${error.message}`);
        resultDiv.innerHTML = `<div class="alert alert-danger">网络错误: ${error.message}</div>`;
    });
}

// 页面加载时自动检查
document.addEventListener('DOMContentLoaded', function() {
    log('RAG调试页面加载完成');
    checkSystemStatus();
});
</script>
{% endblock %}
